package com.hh.service.service.impl.im;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hh.common.constants.Constants;
import com.hh.common.constants.ImConstants;
import com.hh.common.model.im.ImGroup;
import com.hh.common.model.im.ImGroupOwnerAccount;
import com.hh.common.utils.HhUtil;
import com.hh.common.utils.RandomCodeUtils;
import com.hh.common.utils.RestTemplateUtil;
import com.hh.common.vo.im.CommonResultVo;
import com.hh.service.service.im.ImGroupService;
import com.hh.service.dao.im.ImGroupDao;
import com.hh.service.dao.im.ImGroupOwnerAccountDao;
import com.hh.service.service.SystemAttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ImGroupServiceImpl extends BaseImService implements ImGroupService {

    @Resource
    private ImGroupDao dao;

    @Resource
    private ImGroupOwnerAccountDao imGroupOwnerAccountDao;

    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Autowired
    private RestTemplateUtil restTemplateUtil;


    @Override
    public ImGroup getGroupOneNotFull() {
        return dao.getGroupOneNotFull();
    }

    @Override
    public String createGroup() {
        String groupOwnerId;
        //获取一个群主
        ImGroupOwnerAccount oneGroupOwner = imGroupOwnerAccountDao.getOneGroupOwner();
        if(ObjectUtil.isNull(oneGroupOwner)){
            //创建一个群主
            groupOwnerId = createGroupOwner();
        }else {
            groupOwnerId = oneGroupOwner.getAccount();
        }

        String userSig = getAdminUserSig(getIdentifier());
        Integer ranDom = HhUtil.randomCount(11111111, 99999999);
        String url = String.format(ImConstants.CREATE_GROUP_URL,getSdkAppId(),getIdentifier(),userSig,ranDom);
        Map<String,Object> map = new HashMap<>();
        String groupId = RandomCodeUtils.generateShortUuid();
        String avatarUrl = systemAttachmentService.prefixImage(Constants.USER_DEFAULT_AVATAR_CONFIG_KEY);
        map.put("Name","新兰" + groupId);
        map.put("Type","Public");
        map.put("GroupId",groupId);
        map.put("FaceUrl", avatarUrl);
        if(StrUtil.isNotBlank(groupOwnerId)){
            map.put("Owner_Account",groupOwnerId);
        }
        String s = restTemplateUtil.postMapData(url, map);
        CommonResultVo result = JSONObject.parseObject(s, CommonResultVo.class);
        if("FAIL".equals(result.getActionStatus())){
            if(result.getErrorCode() == 10037){
                //该群主创建和加入的群组数量超过了限制
                imGroupOwnerAccountDao.updateFullStatus(groupOwnerId);
            }
            if(result.getErrorCode() == 10058){
                //表示体验版超过100个群的限制
                //发邮件通知管理员
            }
            return "";
        }else {
            return result.getGroupId();

        }

    }

    /**
     * 创建群主账号
     * @return
     */
    @Override
    public String createGroupOwner() {
        String fullUrl = ImConstants.ACCOUNT_IMPORT_URL;
        String avatarUrl = systemAttachmentService.prefixImage(Constants.USER_DEFAULT_AVATAR_CONFIG_KEY);
        String userSig = getAdminUserSig(getIdentifier());
        Integer ranDom = HhUtil.randomCount(11111111, 99999999);
        String url = String.format(fullUrl,getSdkAppId(),getIdentifier(),userSig,ranDom);
        Map<String,Object> map = new HashMap<>();
        String userId = RandomCodeUtils.generateShortUuid();
        map.put("UserID",userId);
        map.put("Nick","新兰" + userId);
        map.put("FaceUrl",avatarUrl);
        String s = restTemplateUtil.postMapData(url, map);
        CommonResultVo result = JSONObject.parseObject(s, CommonResultVo.class);
        if("FAIL".equals(result.getActionStatus())){
            log.error("创建群主账号失败"+result.getErrorInfo());

            if(result.getErrorCode() == 70398){
                //帐号数超限,发邮件通知管理员
            }
            return "";
        }else {
            ImGroupOwnerAccount imGroupOwnerAccount = new ImGroupOwnerAccount();
            imGroupOwnerAccount.setAccount(userId);
            imGroupOwnerAccountDao.insert(imGroupOwnerAccount);
            return userId;
        }
    }

    /**
     * 添加群成员
     * @param imUserId
     * @param groupId
     */
    @Override
    public void addGroupMember(String imUserId, String groupId) {
        String userSig = getAdminUserSig(getIdentifier());
        Integer ranDom = HhUtil.randomCount(11111111, 99999999);
        String url = String.format(ImConstants.ADD_GROUP_MEMBER_URL,getSdkAppId(),getIdentifier(),userSig,ranDom);

        Map<String,Object> map = new HashMap<>();
        map.put("GroupId",groupId);
        List<Map<String,String>> list = new ArrayList<>();
        Map<String,String> memberMap = new HashMap<>();
        memberMap.put("Member_Account",imUserId);
        list.add(memberMap);
        map.put("MemberList",list);
        String s = restTemplateUtil.postMapData(url, map);
        CommonResultVo result = JSONObject.parseObject(s, CommonResultVo.class);

        if("FAIL".equals(result.getActionStatus())){
            //失败了
            if(result.getErrorCode() == 10014){
                //群已经满员
                dao.updateFullStatus(groupId);
            }
        }

    }
}
